<template>
	<view class="">
		<!-- <view class="header">
            <image class="icon" src="/static/icons/store-left.png"></image>
            <view class="title">门店设置</view>
        </view> -->

		<view class="store-bg">
			<image class="store-image" src="https://www.tennoir.ltd/static/icons/store-bg.png"></image>
			<view class="store-logo">
				<image src="https://www.tennoir.ltd/static/icons/store-icon.png" class="logo"></image>
			</view>
		</view>

		<view class="store-settings rounded-corners">
			<view class="store-info">
				<view class="store-details">
					<view class="name row">
						<text class="label">门店名称</text>
						<input v-model="formData.name" class="value" type="text" placeholder="请输入门店名称" />
					</view>

					<view class="flex">
						<!-- <view class="store-row">
                            <text class="label">门店Logo</text>
                            <view class="image-list">
                                <image class="photo-upload" src="https://www.tennoir.ltd/static/upload.png"></image>
                            </view>
                        </view>
                        <view class="store-row">
                            <text class="label">门店照片</text>
                            <view class="image-list">
                                <image class="photo-upload" src="https://www.tennoir.ltd/static/upload.png"></image>
                            </view>
                        </view> -->
						<view class="store-row">
							<text class="label">门店Logo</text>
							<view class="image-list">
								<image class="photo-upload" @click="uploadLogo"
									:src="formData.logo || 'https://www.tennoir.ltd/static/upload.png'"
									mode="aspectFill">
								</image>
							</view>
						</view>
						<view class="store-row">
							<text class="label">门店照片</text>
							<view class="image-list">
								<image class="photo-upload" @click="uploadPhoto"
									:src="formData.images || 'https://www.tennoir.ltd/static/upload.png'"
									mode="aspectFill">
								</image>
							</view>
						</view>
					</view>
				</view>

				<store-picker label="基础服务" placeholder="请选择基础服务" :selected-text="formData.service_ids_text"
					@click="togglePicker('service')" />

				<!-- 营业时间 -->
				<store-picker label="营业时间" placeholder="请选择营业时间" :selected-text="formData.business_hours"
					@click="togglePicker('time')" />



				<view class="store-description">
					<text class="label">门店介绍</text>
					<textarea v-model="formData.content" class="description-input" placeholder="请输入门店介绍..."></textarea>
				</view>



				<!-- 基础服务 -->


				<view class="store-timing">
					<view class="row">
						<text class="label">可提前预定天数</text>
						<input v-model="formData.advancedays" class="value" type="text" placeholder="请输入可提前预定天数" />
					</view>
					<view class="row">
						<text class="label">每天可预定小时</text>
						<input v-model="formData.dayhour" class="value" type="text" placeholder="请输入每天可预定小时" />
					</view>

					<view class="row">
						<text class="label">省/市/区</text>
						<!-- <view @click="showCityPicker" class="value picker-btn">{{ formData.city || '请选择省市区' }}</view> -->
						<view class="picker-region">
							<CityPicker :city="formData.city" @regionSelected="updateCity"></CityPicker>
						</view>
					</view>

					<view v-if="cityPickerVisible" class="city-picker">
						<view class="picker-overlay" @click="hideCityPicker"></view>
						<view class="picker-content">
							<picker mode="multiSelector" :value="pickerValue" :range="cityPickerData"
								@change="onCityChange" @columnchange="onPickerColumnChange">
								<view class="picker-display">{{ pickerDisplay }}</view>
							</picker>
							<view class="picker-buttons">
								<button @click="confirmCity">确定</button>
								<button @click="hideCityPicker">取消</button>
							</view>
						</view>
					</view>

					<view class="row">
						<text class="label">详细地址</text>
						<input v-model="formData.address" class="value" type="text" placeholder="请输入详细地址" />
					</view>
					<!-- <view class="row">
                        <text class="label">纬度</text>
                        <input v-model="formData.latitude" class="value" type="text" placeholder="请输入纬度" />
                    </view>
                    <view class="row">
                        <text class="label">经度</text>
                        <input v-model="formData.longitude" class="value" type="text" placeholder="请输入经度" />
                    </view> -->

					<view class="row">
						<text class="label">联系人</text>
						<input v-model="formData.contacts" class="value" type="text" placeholder="请输入联系人" />
					</view>
					<view class="row">
						<text class="label">联系电话</text>
						<input v-model="formData.phone" class="value" type="text" placeholder="请输入联系电话" />
					</view>
					<view class="row">
						<text class="label">联系微信</text>
						<input v-model="formData.weixin" class="value" type="text" placeholder="请输入联系微信" />
					</view>
				</view>
			</view>

			<view class="submit-btn">
				<view @click="submitForm" class="btn-submit">提交</view>
			</view>
		</view>

		<!-- 弹窗 -->
		<!-- {{pickerVisible.service}} -->
		<!-- {{pickerVisible.time}} -->
		<service-picker v-if="pickerVisible.service" :selected="formData.service_ids" :options="serviceOptions"
			@confirm="onServiceConfirm" @cancel="togglePicker('service')" />
		<time-picker v-if="pickerVisible.time" :start="businessTime.start" :end="businessTime.end"
			@confirm="onTimeConfirm" @cancel="togglePicker('time')" />

	</view>
</template>

<script>
	import CityPicker from './components/CityPicker.vue';

	import StorePicker from './components/StorePicker.vue'; // 通用选择子组件
	import ServicePicker from './components/ServicePicker.vue'; // 基础服务选择子组件
	import TimePicker from './components/TimePicker.vue'; // 时间选择子组件

	import http_config from '@/config/http';

	import {
		mapState,
		mapActions
	} from 'vuex';
	export default {
		components: {
			CityPicker,
			StorePicker,
			ServicePicker,
			TimePicker
		},
		data() {
			return {
				userInfo: {},
				serviceOptions: [ // 基础服务选项列表
					{
						id: 1,
						name: 'WiFi'
					},
					{
						id: 2,
						name: '停车位'
					},
					{
						id: 3,
						name: '充电设施'
					},
					{
						id: 4,
						name: '儿童娱乐区'
					},
					{
						id: 5,
						name: '无障碍通道'
					},
				],
				businessTime: {
					start: '5:00', // 开始时间
					end: '6:00', // 结束时间
				},
				pickerVisible: {
					service: false, // 基础服务弹窗控制
					time: false, // 时间弹窗控制
				},
				formData: {
					id: "", // 门店id
					name: '', // 门店名称
					open_start: '', // 开始营业时间
					open_end: '', // 结束营业时间
					// service_ids_text: '', // 服务描述
					// service_ids: '', // 服务ID
					service_ids: [], // 基础服务ID
					service_ids_text: '', // 基础服务描述
					business_hours: '', // 营业时间描述
					logo: '', // 门店Logo
					images: '', // 门店图片
					contacts: '', // 联系人
					phone: '', // 联系电话
					weixin: '', // 联系微信
					advancedays: '', // 提前预定天数
					dayhour: '', // 每天可预定小时
					city: '', // 省/市/区
					address: '', // 详细地址
					latitude: '', // 纬度
					longitude: '', // 经度
					content: '', // 门店介绍
					status: 'normal' // 状态
				}
			};
		},
		computed: {
			...mapState(['common', 'user'])
		},
		onShow() {
			this.$xyfun.setNavBg();
			this.css = this.$xyfun.css();
			// this.loadRoom();
		},
		onLoad() {
			this.getUserInfo().
			then(res => {
				this.userInfo = res.userInfo;
				// console.log("imagesUrl:" + this.$xyfun.image(userInfo.avatar))
			}).catch(e => {
				console.log(e);
			});
			this.getStoreByUserId()
		},
		methods: {
			...mapActions('user', {
				'getUserInfo': 'getInfo'
			}),
			// 显示或隐藏弹窗
			togglePicker(type) {
				console.log(type);
				this.pickerVisible[type] = !this.pickerVisible[type];

				// 禁用或启用背景页面滚动
				if (this.pickerVisible[type]) {
					if (typeof document !== 'undefined' && document.body) {
						document.body.style.overflow = 'hidden'; // 禁用滚动
					}

					// 清空输入框内容（可以选择性清空某些字段）
					// this.clearFormData(); // 清空输入框数据
				} else {
					if (typeof document !== 'undefined' && document.body) {
						document.body.style.overflow = ''; // 恢复滚动
					}
				}
			},
			// 清空表单数据的特定字段
			clearFormData() {
				this.formData.name = '';
				this.formData.service_ids = [];
				this.formData.business_hours = '';
				this.formData.content = '';
				// 其他字段按需清空
			},
			// 确认基础服务选择
			onServiceConfirm(selectedIds) {
				this.formData.service_ids = [...selectedIds];
				this.formData.service_ids_text = this.serviceOptions
					.filter(option => selectedIds.includes(option.id))
					.map(option => option.name)
					.join(', ');
				this.togglePicker('service');
				console.log(selectedIds)
			},
			// 确认营业时间选择
			onTimeConfirm({
				start,
				end
			}) {
				this.businessTime.start = start;
				this.businessTime.end = end;
				this.formData.business_hours = `${start}-${end}`;
				this.formData.open_start = start;
				this.formData.open_end = end;
				this.togglePicker('time');
			},
			submitForm() {
				// 根据地址获取经纬度
				for (let key in this.formData) {
					if (this.formData[key] === '' && key !== 'service_ids' && key !== 'latitude' && key !== 'longitude' &&
						key !== 'open_start' && key !== 'open_end') {
						uni.showToast({
							title: key + '不得为空',
							icon: 'none'
						});
						return;
					}
				}
				uni.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/',
					method: "POST",
					data: {
						address: this.formData.city + this.formData.address,
						key: 'YX4BZ-ZGYC5-QOKIT-QUGGM-GRIL5-GCFDF'
					},
					success: (res) => {
						this.formData.latitude = res.data.result.location.lat
						this.formData.longitude = res.data.result.location.lng
					}
				});

				if (Array.isArray(this.formData.service_ids)) {
					this.formData.service_ids = this.formData.service_ids.join(",")
				}
				this.$api.post({
					url: '/Store/updateStore ',
					loadingTip: '加载中...',
					data: this.formData,
					success: res => {
						// 修改成功
						// console.log(this.formData)
						// 将更新后的 formData 存储到 'xyvenue:userstore' 本地存储
						uni.setStorageSync('xyvenue:userstore', this.formData);
						uni.showToast({
							title: "设置成功"
						})
					}
				})
			},
			// 上传图片
			async uploadImage(url, type) {
				const that = this;
				uni.showLoading({
					title: '图片上传中...'
				});
				try {
					const res = await new Promise((resolve, reject) => {
						uni.uploadFile({
							url: http_config.base_url + "/api/common/upload",
							filePath: url,
							name: "file",
							header: {
								token: that.userInfo.token,
								'content-type': 'multipart/form-data'
							},
							success: res => {
								resolve(JSON.parse(res.data));
							},
							fail: res => {
								uni.hideLoading();
								that.$xyfun.msg('图片上传失败！');
								if (type === 'logo') {
									that.formData.logo = '';
								} else if (type === 'photo') {
									that.formData.images = '';
								}
								reject(res);
							},
							complete: () => {
								uni.hideLoading();
							}
						});
					});
					if (type === 'logo') {
						this.formData.logo = res.data.fullurl;
					} else if (type === 'photo') {
						this.formData.images = res.data.fullurl;
					}
					return res.data.fullurl;
				} catch (e) {
					console.log(e);
				}
			},
			// 上传门店Logo
			async uploadLogo() {
				uni.chooseImage({
					count: 1, // 只允许选择一张图片
					success: async (res) => {
						const tempFilePaths = res.tempFilePaths;
						await this.uploadImage(tempFilePaths[0], 'logo');
					}
				});
			},
			// 上传门店照片
			async uploadPhoto() {
				uni.chooseImage({
					count: 1, // 只允许选择一张图片
					success: async (res) => {
						const tempFilePaths = res.tempFilePaths;
						await this.uploadImage(tempFilePaths[0], 'photo');
					}
				});
			},
			updateCity(e) {
				this.formData.city = e
			},
			// 获取店铺信息
			getStoreByUserId() {
				this.$api.post({
					url: '/Store/getStoreByUserId',
					loadingTip: '加载中...',
					data: {
						user_id: uni.getStorageSync('xyvenue:user').id,
					},
					success: (res) => {
						uni.setStorageSync('xyvenue:userstore', res);
						this.formData.id = res.id
						this.formData.name = res.name
						// 处理businesshours
						const parts = res.businesshours.split(' - ', 2);
						if (parts.length === 2) {
							this.formData.open_start = parts[0].trim();
							this.formData.open_end = parts[1].trim();
						} else {
							this.formData.open_start = '';
							this.formData.open_end = '';
						}
						this.formData.service_ids = res.service_ids
						const idArray = res.service_ids.split(',').map(Number);
						const names = idArray.map(id => {
							const service = this.serviceOptions.find(s => s.id === id);
							return service ? service.name : '';
						}).filter(name => name !== '');
						this.formData.service_ids_text = names.join(', ');
						this.formData.business_hours = res.businesshours
						this.formData.logo = res.logo
						this.formData.images = res.images[0]
						this.formData.phone = res.phone
						this.formData.weixin = res.weixin
						this.formData.advancedays = res.advancedays
						this.formData.dayhour = res.dayhour
						this.formData.city = res.city
						this.formData.address = res.address
						this.formData.latitude = res.latitude
						this.formData.longitude = res.longitude
						this.formData.content = res.content
						this.formData.status = res.status
						this.formData.contacts = res.contacts
					},
				});
			}
		}
	};
</script>


<style lang="scss" scoped>
	.row {
		display: flex;
		align-items: center;
		margin: 10px 0;
	}

	.label {
		flex: 0 0 100px;
		color: #666;
	}

	.value {
		flex: 1;
		color: #333;
		border-bottom: 1px solid #ddd;
		padding: 5px;
	}

	.picker-btn {
		color: #999;
		cursor: pointer;
	}

	.city-picker {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.4);
		display: flex;
		align-items: flex-end;
	}

	.picker-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.4); // 遮罩层的背景色
		z-index: 999; // 确保遮罩层位于页面的最上层
	}

	.picker-region {
		flex-grow: 1;
		margin-left: 30rpx;
		color: #666;
		font-size: 28rpx;
		border: none;
		background: transparent;
	}

	.picker-content {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background: #fff;
		z-index: 1000; // 确保弹窗内容比遮罩层高
	}

	.picker-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 10px;
	}

	.picker-display {
		padding: 10px;
		border: 1px solid #ddd;
		background: #f9f9f9;
		border-radius: 5px;
		text-align: center;
	}

	.store-settings {
		display: flex;
		flex-direction: column;

		align-items: center;
		justify-content: center;
	}

	.store-timing .row:last-child {
		margin-bottom: 100rpx;
		/* 距离底部的距离 */
	}

	.submit-btn {
		text-align: center;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #65C61D;
		// border-radius: 14rpx;
		padding: 10rpx;
		box-sizing: border-box;
	}

	.btn-submit {
		// width: 200rpx;
		height: 60rpx;
		color: white;
		font-size: 36rpx;
		// border-radius: 14rpx;
		text-align: center;
		line-height: 60rpx;
		cursor: pointer;
	}

	.btn-submit:hover {
		background-color: #65C61D;
	}

	.store-info {
		position: absolute;
		top: 440rpx;
		background-color: #fff;
		padding: 40px;
		z-index: -1;
	}

	.store-row {
		display: flex;
		flex-direction: column;

		.image-list {
			display: flex;
			justify-content: space-between;
			margin-top: -60px;
			/* 添加间距 */
			// flex-wrap: wrap;
			/* 自动换行 */
			// gap: 10px;
			/* 设置元素之间的间距 */
		}

		.photo-upload {
			flex: 0 0 calc(100%);
			/* 每行两个，扣除间距 */
			box-sizing: border-box;
			/* 确保宽度包含内边距和边框 */
		}

		image {
			width: 295rpx;
			height: 181rpx;
		}

	}

	.store-timing,
	.store-booking,
	.store-location,
	.store-contact {
		// margin-bottom: 20px;
		background-color: #fff;
		// padding: 10px;
		border-radius: 8px;
	}

	.header {
		position: absolute;
		/* Position the header above store-bg */
		top: 0;
		/* Align to the top */
		left: 0;
		/* Align to the left */
		width: 100%;
		/* Full width to cover store-bg */
		display: flex;
		/* Layout items in a row */
		align-items: center;
		/* Center items vertically */
		justify-content: space-between;
		/* Adjust spacing between items */
		padding: 10px;
		/* Add some padding */
		background-color: transparent;
		/* Transparent background */
		z-index: 10;
		/* Ensure it's above the store-bg */
	}

	.icon {
		width: 24rpx;
		/* Adjust size of the icon */
		height: 44rpx;
		margin-right: 10px;
		/* Space between icon and the start of the row */
	}

	.title {
		font-weight: bold;
		flex-grow: 1;
		/* Allow title to grow and fill available space */
		text-align: center;
		/* Center the title text */
		font-size: 45rpx;
		/* Adjust font size */
		color: #fff;
		/* Text color */
		margin-left: -100rpx;
		/* Adjust for the icon width to center the text visually */
	}

	.store-bg {
		position: relative;
		/* Position relative to allow header to sit on top */
	}

	.store-image {
		width: 750rpx;
		/* Full width of the parent container */
		height: 505rpx;
		/* Adjust height proportionally */
	}

	.store-logo {
		position: absolute;
		/* Position logo within store-bg */
		top: 50%;
		/* Center vertically */
		left: 50%;
		/* Center horizontally */
		transform: translate(-50%, -50%);
		/* Correct centering offset */
	}

	.store-logo image {
		width: 176rpx;
		height: 176rpx;
	}



	.row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 638rpx;
		height: 88rpx;
		background: #f5f5f5;
		border-radius: 14rpx;
		margin-bottom: 10rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
	}

	.label {
		flex-shrink: 0;
		color: #333;
		font-size: 28rpx;
		font-weight: bold;
		line-height: 90rpx;
	}

	.value {
		flex-grow: 1;
		margin-left: 20rpx;
		color: #666;
		font-size: 28rpx;
		border: none;
		background: transparent;
	}

	.arrow {
		flex-shrink: 0;
		color: #999;
		font-size: 28rpx;
	}

	.store-description {
		width: 638rpx;
		height: 347rpx;
		background: #f5f5f5;
		border-radius: 14rpx;
		padding: 15rpx;
		box-sizing: border-box;
		margin: 20rpx;
		/* 增加间距 */
	}

	.description-input {
		width: 100%;
		height: 100%;
		border: none;
		background: transparent;
		font-size: 28rpx;
		color: #333;
		resize: none;
		/* 禁止拖动调整大小 */
		outline: none;
		/* 移除聚焦时的边框 */
	}

	.photo-upload {
		width: 120rpx;
		height: 120rpx;
		// background-color: #65C61D;
		border: 2rpx solid #65C61D;
		color: white;
		font-size: 36rpx;
		border-radius: 14rpx;
		text-align: center;
		line-height: 120rpx;
		cursor: pointer;
		margin-right: 10rpx;
	}

	.photo-upload:hover {
		// background-color: #65C61D;
		border: 2rpx solid #65C61D;
	}

	.store-details {
		margin-bottom: 40rpx;
	}

	.flex {
		display: flex;
		justify-content: space-between;
	}
</style>